//
//  VPViewController.m
//  VPImageCropperDemo
//
//  Created by Vinson.D.Warm on 1/13/14.
//  Copyright (c) 2014 Vinson.D.Warm. All rights reserved.
//

#import "VPViewController.h"
#import "VPImageCropperViewController.h"
#import "ProfileTableViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AppDelegate.h"



@interface VPViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, VPImageCropperDelegate>

@property (nonatomic, strong) UIImageView *portraitImageView;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *fans;
@property (nonatomic, strong) NSString *follow;
@property (nonatomic, strong) NSString *works;

@end

@implementation VPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    int y= 50;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,y+50,MAINWIDTH,80)];
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0,y+240,MAINWIDTH,4)];
    
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(80, y+70, 210, 20)];
    UILabel *me = [[UILabel alloc]initWithFrame:CGRectMake(160, y+20, 100, 20)];
    
    UILabel *followLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, y+150, 60, 20)];
    UILabel *fansLabel =[[UILabel alloc]initWithFrame:CGRectMake(70,y+150,60,20)];
    UILabel *worksLabel = [[UILabel alloc]initWithFrame:CGRectMake(140,y+150,60,20)];
    UILabel *addLabel = [[UILabel alloc]initWithFrame:CGRectMake(190, y+150, 60, 20)];
    
    UILabel *follow = [[UILabel alloc]initWithFrame:CGRectMake(20, y+130, 60, 20)];
    UILabel *fans =[[UILabel alloc]initWithFrame:CGRectMake(80,y+130,60,20)];
    UILabel *works = [[UILabel alloc]initWithFrame:CGRectMake(150,y+130,60,20)];
    
    UILabel *all = [[UILabel alloc]initWithFrame:CGRectMake(20,y+ 215, 120, 20)];
    
    
    UITextField *searchBar = [[UITextField alloc]initWithFrame:CGRectMake(40, y+180, 340, 30)];
    searchBar.width = 300;
    searchBar.height = 30;
    
    // 设置背景
    searchBar.background = [UIImage resizedImage:@"searchbar_textfield_background"];
    
    // 设置内容 -- 垂直居中
    searchBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    // 设置左边显示一个放大镜
    UIImageView *leftView = [[UIImageView alloc] init];
    leftView.image = [UIImage imageWithName:@"searchbar_textfield_search_icon"];
    leftView.width = searchBar.height;
    leftView.height = searchBar.height;
    // 设置leftView的内容居中
    leftView.contentMode = UIViewContentModeCenter;
    searchBar.leftView = leftView;
    
    // 设置左边的view永远显示
    searchBar.leftViewMode = UITextFieldViewModeAlways;
    
    // 设置右边永远显示清除按钮
    searchBar.clearButtonMode = UITextFieldViewModeAlways;
    // 设置预设文字
    searchBar.Placeholder = @"搜索我的作品";

    
    self.name= @"罗玉凤（凤姐）";
    followLabel.text = @"关注";
    fansLabel.text = @"被关注";
    worksLabel.text = @"作品";
    addLabel.text=@"添加";
    self.follow = @"100";
    self.fans = @"991";
    self.works = @"20";
    self.name =@"罗玉凤（凤姐）";
    
    follow.text = self.follow;
    fans.text = self.fans;
    works.text = self.works;
    name.text = self.name;
    
    me.text = @"我的";
    all.text = @"全部作品";
    
    me.textColor=[UIColor whiteColor];
    fans.textColor=[UIColor grayColor];
    follow.textColor=[UIColor grayColor];
    works.textColor=[UIColor grayColor];
    fansLabel.textColor=[UIColor grayColor];
    followLabel.textColor=[UIColor grayColor];
    worksLabel.textColor=[UIColor grayColor];
    addLabel.textColor =[UIColor grayColor];
    name.textColor = MTColor(20.0, 20.0, 20.0, 1.0);
    view.backgroundColor = MTColor(220.0, 220.0, 220.0, 1.0);
    view2.backgroundColor = MTColor(220.0, 220.0, 220.0, 1.0);
    all.textColor = MTColor(120.0, 120.0, 120.0, 1.0);

    
    
    [self.view addSubview:view];
    [self.view addSubview:view2];
    [self.view addSubview:name];
    [self.view addSubview:fans];
    [self.view addSubview:fansLabel];
    [self.view addSubview:works];
    [self.view addSubview:worksLabel];
    [self.view addSubview:follow];
    [self.view addSubview:followLabel];
    [self.view addSubview:self.portraitImageView];
    [self.view addSubview:searchBar];
    [self.view addSubview:me];
    [self.view addSubview:all];
    [self.view addSubview:addLabel];
    [self loadPortrait];


}
- (void)loadPortrait {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        NSURL *portraitUrl = [NSURL URLWithString:@"http://picview01.baomihua.com/photos/20120119/m_14_634626046352187500_36036466.jpg"];
        UIImage *protraitImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:portraitUrl]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.portraitImageView.image = protraitImg;
        });
    });
}

- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.portraitImageView.image = editedImage;
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark portraitImageView getter
- (UIImageView *)portraitImageView {
    if (!_portraitImageView) {
        CGFloat w = 50.0f; CGFloat h = w;
        CGFloat x = 20;
        CGFloat y = 60;
        _portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y+50, w, h)];
        [_portraitImageView.layer setCornerRadius:(_portraitImageView.frame.size.height/2)];
        [_portraitImageView.layer setMasksToBounds:YES];
        [_portraitImageView setContentMode:UIViewContentModeScaleAspectFill];
        [_portraitImageView setClipsToBounds:YES];
        _portraitImageView.layer.shadowColor = [UIColor blackColor].CGColor;
        _portraitImageView.layer.shadowOffset = CGSizeMake(4, 4);
        _portraitImageView.layer.shadowOpacity = 0.5;
        _portraitImageView.layer.shadowRadius = 2.0;
        _portraitImageView.layer.borderColor = [[UIColor blackColor] CGColor];
        _portraitImageView.layer.borderWidth = 2.0f;
        _portraitImageView.userInteractionEnabled = YES;
        _portraitImageView.backgroundColor = [UIColor blackColor];
        UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
        [_portraitImageView addGestureRecognizer:portraitTap];
    }
    return _portraitImageView;
}

@end
